#include"Stack.h"

Stack* STCreate()
{
	Stack* st = (Stack*)malloc(sizeof(Stack));
	if (NULL == st)
	{
		perror("malloc failed");
		exit(-1);
	}
	st->a = NULL;
	st->capacity = st->top = 0;
	return st;
}

void STDestroy(Stack* st)
{
	assert(st);
	free(st->a);
	st->a = NULL;
	st->capacity = st->top =  0;
	free(st);
}

void STPush(Stack* st, STDataType x)
{
	assert(st);
	if (st->capacity == st->top)
	{
		int newcapacity = st->capacity == 0 ? 4 : st->capacity * 2;
		STDataType* temp = (STDataType*)realloc(st->a, sizeof(STDataType) * newcapacity);
		if (NULL == temp)
		{
			perror("realloc failed");
			exit(-1);
		}
		st->a = temp;
		st->capacity = newcapacity;
	}
	st->a[st->top] = x;
	++st->top;
}

STDataType STPop(Stack* st)
{
	assert(st);
	assert(st->top);
	STDataType ret = STTop(st);
	--st->top;
	return ret;
}

STDataType STTop(Stack* st)
{
	assert(st);
	assert(st->top);
	return st->a[st->top - 1];
}

int STSize(Stack* st)
{
	return st->top;
}

bool STEmpty(Stack* st)
{
	assert(st);
	return st->top == 0;
}
